﻿#region << 文件说明 >>

/*----------------------------------------------------------------
 * 命名空间：Vampirewal.Core.WebApi.Models.ApiResultProvider
 * 唯一标识：ebf00831-a5eb-43ca-8fab-49a3c5f37d22
 * 文件名：VampirewalApiResultProvider
 *
 * 创建者：杨程
 * 电子邮箱：235160615@qq.com
 * 创建时间：2023/10/8 9:34:42
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/

#endregion << 文件说明 >>

namespace Vampirewal.Core.WebApi;

/// <summary>
/// 全局返回值拦截
/// </summary>
internal sealed class VampirewalApiResultProvider : IVampirewalApiResultProvider
{
    /// <summary>
    /// 构造函数
    /// </summary>
    public VampirewalApiResultProvider()
    {
    }

    public async Task<string> OnResponseStatusCodes(int statusCode, bool succeeded = true, object data = default, object errorInfo = default)
    {
        return await Task.Run(() =>
        {
            string response = string.Empty;

            switch (statusCode)
            {
                case 200:
                    response = JsonSerializer.Serialize(RESTfulResult(statusCode, true, data));
                    break;
                // 处理 401 状态码
                case 401:
                    response = JsonSerializer.Serialize(RESTfulResult(statusCode, false, errors: "401 未经授权，请联系管理员授权"));
                    break;
                // 处理 403 状态码
                case 403:
                    response = JsonSerializer.Serialize(RESTfulResult(statusCode, false, errors: "403 禁止访问，没有权限"));
                    break;

                case 404:
                    response = JsonSerializer.Serialize(RESTfulResult(statusCode, false, errors: errorInfo));
                    break;

                case 500:
                    response = JsonSerializer.Serialize(RESTfulResult(statusCode, false, errors: errorInfo));
                    break;

                default: break;
            }

            return Task.FromResult(response);
        });
    }

    public async Task OnErrorResponse(HttpListenerContext context, VampirewalWebApiException exc)
    {
        context.Response.StatusCode = exc.ErrorCode;
        await context.Response.WriteAsJsonAsync(RESTfulResult(exc.ErrorCode, false, errors: exc));
    }

    public async Task OnSuccessResponse(HttpListenerContext context,object data)
    {
        await context.Response.WriteAsJsonAsync(RESTfulResult(200, true, data));
    }

    /// <summary>
    /// 返回 RESTful 风格结果集
    /// </summary>
    /// <param name="statusCode"></param>
    /// <param name="succeeded"></param>
    /// <param name="data"></param>
    /// <param name="errors"></param>
    /// <returns></returns>
    private ApiResult<object> RESTfulResult(int statusCode, bool succeeded = default, object data = default, object errors = default)
    {
        return new ApiResult<object>
        {
            Code = statusCode,
            Message = errors is string str ? str : JsonSerializer.Serialize(errors),
            Data = data,
            Type = succeeded ? "success" : "error",
            Time = DateTime.Now
        };
    }
}